package com.asiainfo.demo.dao.impl;

import com.asiainfo.demo.dao.idao.iCard;
import com.asiainfo.demo.dao.roles.Card;

import java.sql.*;
import java.util.ArrayList;

public class CardImpl implements iCard {
    private Connection con = null;
    private PreparedStatement ps = null;

    public CardImpl(Connection con){
        this.con = con;
    }

    @Override
    public boolean insertCard(Card card) throws SQLException {
        String sql = "INSERT INTO CARD(CARD_TYPE, CARD_VALID) VALUES (?, ?);";

        ps = con.prepareStatement(sql);
        ps.setByte(1, card.getCardType());
        ps.setByte(2, card.getCardValid());

        return ps.executeUpdate() > 0;
    }

    @Override
    public Card findCardByID(int cardID) throws SQLException {
        String sql = "SELECT CARD_TYPE, CARD_VALID FROM CARD WHERE CARD_ID=?;";
        Card resCard = null;

        ps = con.prepareStatement(sql);
        ps.setInt(1, cardID);

        ResultSet resultSet = ps.executeQuery();
        if(resultSet.next()){
            resCard = new Card();
            resCard.setCardID(cardID);
            resCard.setCardType(resultSet.getByte("CARD_TYPE"));
            resCard.setCardValid(resultSet.getByte("CARD_VALID"));
        }

        return resCard;
    }

    @Override
    public ArrayList<Card> findAllCards() throws SQLException {
        String sql = "SELECT * FROM CARD;";

        ps = con.prepareStatement(sql);

        return resultSetToCard(ps);
    }

    @Override
    public boolean changeValid(int cardID, byte newStatus) throws SQLException {
        String sql = "UPDATE CARD SET CARD_VALID = ? WHERE CARD_ID = ?;";

        ps = con.prepareStatement(sql);

        ps.setByte(1, newStatus);
        ps.setInt(2, cardID);

        return ps.executeUpdate() > 0;
    }

    @Override
    public boolean changeType(int cardID, byte newType) throws SQLException {
        String sql = "UPDATE CARD SET CARD_TYPE = ? WHERE CARD_ID = ?;";

        ps = con.prepareStatement(sql);

        ps.setByte(1, newType);
        ps.setInt(2, cardID);

        return ps.executeUpdate() > 0;
    }

    @Override
    public int findMaxCardID() throws Exception {
        String sql = "SELECT MAX(CARD_ID) FROM CARD";
        ps = con.prepareStatement(sql);

        ArrayList<Card> cards = resultSetToCard(ps);
        if(cards.size() < 1){
            return -1;
        }

        return cards.get(0).getCardID();
    }

    private ArrayList<Card> resultSetToCard(PreparedStatement ps) throws SQLException{
        ResultSet resultSet = ps.executeQuery();
        ArrayList<Card> resCards = new ArrayList<>();

        while (resultSet.next()){
            Card resCard = new Card();
            resCard.setCardID(resultSet.getInt("CARD_ID"));
            resCard.setCardType(resultSet.getByte("CARD_TYPE"));
            resCard.setCardValid(resultSet.getByte("CARD_VALID"));
            resCards.add(resCard);
        }

        return resCards;
    }
}
